package com.hongawen.channel.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * @author hongawen
 * @version 1.0
 * @data 2025/4/30 10:42
 */
public class ServerSocketBlock {

    /**
     * 简介：使用nio来理解阻塞模式，单线程
     *
     * @param args .
     */
    public static void main(String[] args) {
        // 0. 准备ByteBuffer读数据，暂不考虑长度超过1024的数据
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        // 1.创建一个serverSocketChannel服务端
        try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()) {
            // 2.指定服务端监听某个端口
            serverSocketChannel.bind(new InetSocketAddress(8818));
            // 3.准备链接通道
            List<SocketChannel> socketChannels = new ArrayList<>();
            while (true) {
                // 4.监听客户端连接，如果没有连接，则阻塞
                System.out.println("等待客户端连接...");
                // 阻塞
                SocketChannel socketChannel = serverSocketChannel.accept();
                System.out.println("客户端连接成功" + socketChannel.toString());
                socketChannels.add(socketChannel);
                // 5.遍历所有socketChannel，并读取数据
                for (SocketChannel sc : socketChannels) {
                    // 5.读取数据
                    System.out.println("准备读取数据...");
                    // 阻塞
                    int read = sc.read(buffer);
                    System.out.println("读到数据");
                    if (read > 0) {
                        buffer.flip();
                        System.out.println("客户端发送的数据是：" + new String(buffer.array(), 0, read));
                    }
                    buffer.clear();
                }
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

}
